package fragments;

import java.util.ArrayList;

import model.HeroCombo;
import model.HeroComboFactory;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.dotalanecombos.ComboActivity;
import com.example.dotalanecombos.ComboPagerActivity;
import com.example.dotalanecombos.R;

public class HeroListFragment extends ListFragment {

	private ArrayList<HeroCombo> heroCombo;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getActivity().setTitle(R.string.hero_list_title);
		heroCombo = HeroComboFactory.get(getActivity()).getCombos();

		HeroAdapter adapter = new HeroAdapter(heroCombo);
		setListAdapter(adapter);
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		HeroCombo heroCombo = ((HeroAdapter) getListAdapter()).getItem(position);
		Log.d("CLICKED", heroCombo.getMainHero().getHeroName() + " was clicked");

		// Start ComboActivity
		Intent i = new Intent(getActivity(), ComboPagerActivity.class);
		i.putExtra(ComboFragment.EXTRA_COMBO, heroCombo.getMainHero().getHeroName());
		startActivity(i);
	}

	private class HeroAdapter extends ArrayAdapter<HeroCombo> {

		public HeroAdapter(ArrayList<HeroCombo> heroCombos) {
			super(getActivity(), 0, heroCombos);

		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// If we weren't given a view, inflate one
			if (convertView == null) {
				convertView = getActivity().getLayoutInflater().inflate(R.layout.hero_list_item, null);
			}

			// Configure the view for this Crime
			HeroCombo heroCombo = getItem(position);

			TextView heroName = (TextView) convertView.findViewById(R.id.hero_list_name);
			heroName.setText(heroCombo.getMainHero().getHeroName());

			TextView heroRole = (TextView) convertView.findViewById(R.id.hero_list_role);
			heroRole.setText(heroCombo.getMainHero().getHeroRole());

			ImageView heroPortrait = (ImageView) convertView.findViewById(R.id.hero_list_image);
			int imageId = getResources().getIdentifier(heroCombo.getMainHero().getHeroName().toLowerCase(), "drawable",
					convertView.getContext().getPackageName());
			heroPortrait.setImageResource(imageId);

			return convertView;
		}
	}

}
